<template>
	<view class="bgbox po_rel" @click="state.thiscode=null,state.chatinputmoretype=false">
		<!-- <un-navbar :titleText="state.userinfo.targetId" bgColor="rgba(0,0,0,0)">
			<template #content>
				<image src="../../static/image/chat/diandian.png" class="addsclass po_abs"></image>
			</template>
		</un-navbar> -->
		<!-- store.state.friendinfo[state.userinfo.targetId].remark_name -->
		<un-navbar :titleText="store.state.friendinfo[state.userinfo.targetId]?.remark_name || state.userinfo.targetId"
			:bgImgtype="2">
			<template #content v-if="store.state.myinfo.system_code!=state.userinfo.targetId">
				<image src="../../static/image/chat/diandian.png" class="addsclass po_abs" @click="goset(1)"></image>
			</template>
		</un-navbar>
		<!-- <view id="scrollview" style="background-color: #F1F4F4;"> -->
		<view id="scrollview" class="scrollview"
			:style="`background-image: url(${store.state.bg_photo[state.userinfo.targetId]||''})`">
			<!-- <list :style="`height:${state.scrollviewheight-state.inputboxsheight/2}px`" :scrollable="false" class="bg_yellow">
				<cell v-for="item in store.state.getMessages" render-reverse-position>
					<view class="flex pa20">
						<image
							src="https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
							class="userimgs"></image>
						<view class="dialoguecontent bg_white ma_left14 fs32 break_all pa_tb24 pa_left24 pa_right20">
							{{item.text}}
						</view>
					</view>
					
				</cell>
				<view style="height: 150upx;"></view> -->

			<!-- <cell v-for="(item,index) in store.state.getMessages" :key="item.messageUId">
					<view class="flex pa20">
						<image
							src="https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
							class="userimgs"></image>
						<view class="dialoguecontent bg_white ma_left14 fs32 break_all pa_tb24 pa_left24 pa_right20">
							{{item.text}}
						</view>
					</view>
				</cell> -->


			<!-- </list> -->

			<scroll-view scroll-y="true" @scrolltolower="loadMore" upper-threshold="100" class="wi_100 flex"
				style="transform: rotate(180deg);" :style="`height:${state.scrollviewheight-state.inputboxsheight }px`">
				<!-- <scroll-view scroll-y="true" @scrolltolower="loadMore" upper-threshold="100" class="wi_100 flex"
				style="transform: rotate(180deg);" :style="`height:${state.scrollviewheight-state.inputboxsheight }px`"
				:scroll-into-view="scrollLeftTop"> -->
				<!-- 	<view class="pa20" v-for="item in store.state.getMessages">
					<view class="flex">
						<image
							src="https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
							class="userimgs"></image>
						<view class="dialoguecontent bg_white ma_left14 fs32 break_all pa_tb24 pa_left24 pa_right20">
							{{item.text}}
						</view>
					</view>
				</view> -->

				<!-- :class="store.state.myinfo.system_code==item.senderUserId?'justify_end':''" :style="`opacity:${lastids!=index?1:0}`"> -->
				<view v-for="(item,index) in getMessages" style="transform: rotate(180deg);" class="pa_top10">
					<view class="flex justify_center f_s24 te_black9 pa10" v-if="shouldShowTime(index)">{{gettimes(item.sentTime)}}</view>
					<view class="pa20 flex ma_tb30">
						<view class="multipleclass" v-if="state.onmultip"></view>
						<image class="multipleclass2" v-if="state.onmultip"
							src="../../static/image/chat/chatduogous.png"></image>
						<view class="flex flex1"
							:class="store.state.myinfo.system_code==item.senderUserId?'justify_end':''">
							
							<!-- 	<view class="flex flex1"
							:class="store.state.myinfo.system_code==item.senderUserId?'justify_end':''"
							:style="`opacity:${lastids!=index?1:0}`"> -->
							<image v-if="item.direction==1"
								@click="store.state.myinfo.system_code!=item.senderUserId?goset(2):''"
								:src="(store.state.friendinfo[item.targetId]?.avatar || 'https://vpay-static.oss-cn-shenzhen.aliyuncs.com/static/unmanned/images/main/morentouxiang.png' )+'?x-oss-process=image/resize,p_30'"
								class="userimgs ma_right14"></image>
								
							<view v-if="item.sentStatus==1&&item.direction==0" class="flex f_s24 te_blackccc align_center ma_right10">发送失败</view>
							<view @longpress="longpress($event,item)" :style="`z-index:${index};`" class="po_rel">
								<!-- 个人名片消息 -->
								<view v-if="item.messageType==1&&item.identifier=='chat_diy'" class="ov_hidden"
									:class="item.direction==1?'grmpclass1':'grmpclass2'" @click="gouserinfo(item)">
									<view class="pa24 colorf9 te_black9 ">
										个人名片
									</view>
									<view class="pa24 bg_white flex align_center">
										<image :src="(item.fields.img||'https://vpay-static.oss-cn-shenzhen.aliyuncs.com/static/unmanned/images/main/morentouxiang.png')+'?x-oss-process=image/resize,p_30'"
											class="userimgs ma_right14"></image>
										<view>
											{{item.fields.name}}
										</view>
									</view>
								</view>

								<!-- 普通文本消息 -->
								<view v-if="item.messageType==2"
									:class="item.direction==0?'dialoguecontent2 te_white':'dialoguecontent te_black'"
									class=" f_s32 break_all pa_tb24 pa_left24 pa_right20">{{item.text}}</view>

								<!-- 图片消息 -->
								<image v-if="item.messageType==4"
									:src="'data:image/png;base64,'+item.thumbnailBase64String" class=" bo_radius10"
									style="max-width: 300upx; max-height: 300upx;" mode="heightFix"
									@click="openimgs(item)"></image>
								<view v-show="state.thiscode== item.sentTime+item.messageUId"
									:class="item.direction==1?'operateclass2':'operateclass1'" class=" po_abs flex">
									<view :class="item.direction==1?'addboxssj1':'addboxssj2'"></view>
									<view class="flex flex_column align_center ma_top10 ma_lr20"
										v-if="item.messageType==2"
										@click.stop="oncopy(item),state.chatinputmoretype=false,state.thiscode=null">
										<image src="../../static/image/chat/chatfz.png" class="operateclassimg">
										</image>
										<view class="f_s24 te_white mt nowraps">复制</view>
									</view>
									<view class="flex flex_column align_center ma_top10 ma_lr20"
										v-if="item.messageType==2||item.messageType==4"
										@click.stop="oncollect(item,item.direction),state.chatinputmoretype=false,state.thiscode=null">
										<image src="../../static/image/chat/chatsc.png" class="operateclassimg">
										</image>
										<view class="f_s24 te_white nowraps">收藏</view>
									</view>
									<view class="flex flex_column align_center ma_top10 ma_lr20"
										@click.stop="ondelete(item),state.chatinputmoretype=false,state.thiscode=null">
										<image src="../../static/image/chat/chatshanc.png" class="operateclassimg">
										</image>
										<view class="f_s24 te_white nowraps">删除</view>
									</view>
									<view class="flex flex_column align_center ma_top10 ma_lr20"
										@click.stop="onforward(item),state.chatinputmoretype=false,state.thiscode=null">
										<image src="../../static/image/chat/chatzf.png" class="operateclassimg">
										</image>
										<view class="f_s24 te_white nowraps">转发</view>
									</view>
									<!-- <view class="flex flex_column align_center ma_top10 ma_lr20"
										@click.stop="onmultipfun(item),state.chatinputmoretype=false,state.thiscode=null">
										<image src="../../static/image/chat/chatdxz.png" class="operateclassimg">
										</image>
										<view class="f_s24 te_white nowraps">多选</view>
									</view> -->
								</view>
							</view>
							<image v-if="item.direction==0"
								:src="(store.state.myinfo?.avatar ||'https://vpay-static.oss-cn-shenzhen.aliyuncs.com/static/unmanned/images/main/morentouxiang.png')+'?x-oss-process=image/resize,p_30'"
								class="userimgs ma_left14"></image>

						</view>

						<!-- <view class="flex" v-else :style="`opacity:${lastids!=index?1:0}`">
							<image
								src="https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
								class="userimgs"></image>
						
							<view
								class="dialoguecontent bg_white ma_left14 fs32 break_all pa_tb24 pa_left24 pa_right20">
								{{item.text}}
							</view>
						</view> -->
					</view>
				</view>

				<!-- <view style="height: 10upx;" id="lastid">
				</view> -->
			</scroll-view>
		</view>
		<view id="inputboxs" class="inputboxs po_fixed wi_100"
			@click="state.thiscode=null,state.chatinputmoretype=false"
			:style="`padding-bottom:${navigationinfo.bottomheight}px`">
			<view class="pa20 flex align_center">
				<view class="flex align_center flex1 inputclassbox bg_white">
					<image src="../../static/image/chat/bottomfsbq.png" class="bottomfsbq ma_lr20"></image>
					<input type="textarea" @confirm="state.content?doSearch(1):''" placeholder="回复消息"
						confirm-type="send" class="flex1 ma_right20 fs32" v-model="state.content" cursor-spacing="100"
						:adjust-position="true" />
				</view>
				<image :src="`../../static/image/chat/${state.chatinputmoretype?'inputclose':'adds'}.png`"
					class="bottomfsbq ma_left20" @click.stop="state.chatinputmoretype=!state.chatinputmoretype"></image>
			</view>
			<view class="flex justify_between pa_lr50 ma_top20 pa_bottom50" v-if="state.chatinputmoretype">
				<view class="flex flex_column align_center">
					<image src="../../static/image/chat/chatinputzp.png" class="chatinputimg"
						@click.stop="senimgfun(1)">
					</image>
					<view class="ma_top20 f_s24">
						照片
					</view>
				</view>
				<view class="flex flex_column align_center">
					<image src="../../static/image/chat/chatinputps.png" class="chatinputimg"
						@click.stop="senimgfun(2)"></image>
					<view class="ma_top20 f_s24">
						拍摄
					</view>
				</view>
				<view class="flex flex_column align_center">
					<image src="../../static/image/chat/chatinputgrmp.png" class="chatinputimg"
						@click.stop="doSearch(2)"></image>
					<view class="ma_top20 f_s24">
						个人名片
					</view>
				</view>
				<view class="flex flex_column align_center">
					<image src="../../static/image/chat/chatinputsc.png" class="chatinputimg" @click.stop="goCollection"></image>
					<view class="ma_top20 f_s24">
						收藏
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { friend_is_friend } from "@/api/addressbook";


	import { showToast, getscrollviewheight, throttle, debounce } from '@/utils/utils'
	import { onLoad, onShow, onUnload, onReady } from '@dcloudio/uni-app'
	import { ref, reactive, getCurrentInstance, watch, nextTick, computed } from 'vue'
	import { friend_info } from '@/api/addressbook'
	import { myadd_favourite } from '@/api/chat'



	import { useStore } from 'vuex'
	const store = useStore()
	const instance = getCurrentInstance(); // 获取组件实例
	onReady(async () => {
		state.scrollviewheight = await getscrollviewheight('#scrollview', instance)

		let query = uni.createSelectorQuery().in(instance);
		query.select("#inputboxs").boundingClientRect((data : any) => {
			//console.log(data)
			state.inputboxsheight = data.height
		}).exec();

		// scrollLeftTop.value = null
		// setTimeout(() => {
		// 	scrollLeftTop.value = null
		// 		setTimeout(() => {
		// 			scrollLeftTop.value = 'lastid'		
		// 		}, 1000)
		// }, 1000)

		// let obj = store.state.getMessages;
		// let keys = Object.keys(obj);
		// let lastKey = keys[keys.length - 1];
	})

	const openimgs = (e) => {
		console.log(e)
		uni.previewImage({
			urls: [e.remote],
			longPressActions: {
				itemList: ['保存图片'],
				success: function (data) {
					uni.downloadFile({
						url: e, //仅为示例，并非真实的资源
						success: (res) => {
							if (res.statusCode === 200) {
								console.log(res);
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: function () {
										uni.showToast({
											title: '保存成功',
											icon: 'success',
											duration: 2000
										});
									}
								});
							}
						}
					});


				},
				fail: function (err) {
					console.log(err.errMsg);
				}
			}
		});
	}
	
	
	const shouldShowTime= (index) =>{
      if (getMessages.value.length-1 === index) {
        return true;
      }
      const currentTime = getMessages.value[index].sentTime;
      const prevTime = getMessages.value[index +1].sentTime;
      // 10 分钟的毫秒数
      const tenMinutes = 10 * 60 * 1000; 
	  // console.log(getMessages.value[index])
      return currentTime - prevTime > tenMinutes;
    }
	
	const ondelete = (item)=>{
		
		uni.showModal({
			title: '提示',
			content: '确认删除此条消息？',
			success: function (res) {
				if (res.confirm) {
					console.log(item)
					deletas()
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		
		let deletas = async()=>{
			console.log(item)
			let callback = {
			onMessagesDeleted:(res) => {
				store.commit('deletegetMessages',{
					messageUId:item.messageUId
				})
				uni.showToast({
					title: '删除成功',
					icon: 'success',
					duration: 2000
				});
			//...
			}};
			let code = await store.state.engine.deleteMessages(1, state.userinfo.targetId, null,[item], callback);
		}
		
		
	}	
	
	
	const goCollection = () => {
		uni.navigateTo({
			url: '/subPackages/my/collection/index?type=1&targetId='+state.userinfo.targetId
		})
	}
	
	
	// setTimeout(()=>{
	// 	console.log(store.state.bg_photo[state.userinfo.targetId])
	// },3000)
	// const getMessages = computed(() => { 
	// 	// [...this.items].reverse();
	//   return [...store.state.getMessages].reverse()
	// })

	const getMessages = computed(() => {
		// [...this.items].reverse();
		clearUnreadCount()
		return store.state.getMessages
	})
	
	
	const clearUnreadCount = async()=>{
		let callback = {
			onUnreadCountCleared: (res) => {
				console.log('清除未读数----',res)
			}
		};
		let code = await store.state.engine.clearUnreadCount(1,state.userinfo.targetId, null,  store.state.getMessages[0]?.sentTime+1000 ||1840554150850 , callback);
	}
	
	
	
	const gettimes = (timestamp) => {


		const targetDate = new Date(timestamp);
		const now = new Date();
		const yesterday = new Date(now);
		yesterday.setDate(now.getDate() - 1);

		// 获取目标时间的年月日时分
		const targetYear = targetDate.getFullYear();
		const targetMonth = targetDate.getMonth() + 1;
		const targetDay = targetDate.getDate();
		const targetHour = targetDate.getHours();
		const targetMinute = targetDate.getMinutes();

		// 格式化时分
		const formattedTime = `${targetHour < 10 ? '0' : ''}${targetHour}:${targetMinute < 10 ? '0' : ''}${targetMinute}`;

		// 判断是否是今天
		if (
			targetYear === now.getFullYear() &&
			targetMonth === now.getMonth() + 1 &&
			targetDay === now.getDate()
		) {
			return '今天' + formattedTime;
		}

		// 判断是否是昨天
		if (
			targetYear === yesterday.getFullYear() &&
			targetMonth === yesterday.getMonth() + 1 &&
			targetDay === yesterday.getDate()
		) {
			return '昨天' + formattedTime;
		}

		// 判断是否是一周内
		const oneWeekAgo = new Date(now);
		oneWeekAgo.setDate(now.getDate() - 7);
		if (targetDate > oneWeekAgo) {
			const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
			const dayOfWeek = daysOfWeek[targetDate.getDay()];
			return `${dayOfWeek} ${formattedTime}`;
		}

		// 都不是，显示年月日
		return `${targetYear}-${targetMonth < 10 ? '0' : ''}${targetMonth}-${targetDay < 10 ? '0' : ''}${targetDay}`;

	}


	const lastids = ref<any>(null)



	const gouserinfo = (item) => {

		friend_is_friend({
			system_code: item.fields.system_code
		}).then((res) => {
			if (res.data.is_friend) {
				uni.navigateTo({
					url: '/subPackages/addressbook/userinfo/index?type=1&portaltype=3&system_code=' + item.fields.system_code
				})
			} else {
				uni.navigateTo({
					url: '/subPackages/addressbook/userinfo/index?unique_code=' + item.fields.system_code
				})
			}
		}).catch((err) => {
			uni.showToast({
				title: err,
				icon: 'none'
			})
		})

	}





	const oncollect = (item, type) => {
		let data = {
			title: '来自于-' + (type == 1 ? state.userinfo.remark_name : '自己'),
			content: item.messageType == 2 ? item.text : item.remote,
			source_id: item.messageUId,
			favourite_type: item.messageType == 2 ? 'text' : item.messageType == 4 ? 'picture' : ''
		}

		console.log(data)
		myadd_favourite(data).then(res => {
			state.thiscode = null
			uni.showToast({
				title: '收藏成功',
				icon: 'success',
				duration: 2000
			});
		})
	}

	const onmultipfun = () => {
		state.onmultip = true
	}

	const onforward = (item) => {
		console.log(item)
		uni.setStorageSync('forward', [item])
		if (item.messageType == 4) {

			uni.getImageInfo({
				src: item.remote,
				success: function (image) {
					let datas = uni.getStorageSync('forward')
					datas[0].localurl  =image.path
					uni.setStorageSync('forward', datas)
					console.log('datasdatas',datas)
					uni.navigateTo({
						url: '/pages/chat/forward'
					})
				}, fail: function (err) {
					uni.setStorageSync('forward', null)
					uni.showToast({
						title: '图片已过期或损坏',
						icon: 'none',
						duration: 2000
					});
				}
			});


			//let datas = uni.getStorageSync('forward')
		} else if (item.messageType == 2||item.messageType == 1) {
			uni.navigateTo({
				url: '/pages/chat/forward'
			})
		}
		


	}
	//sentTime
	const longpress = (e, item) => {
		console.log('eeeeeeeeeeeeeeee', e)
		console.log('itemitemitemitemitem', item)
		state.thiscode = item.sentTime + item.messageUId
	}
	// setInterval(()=>{
	// 	console.log('222222222222222222222',store.state.friendinfo)
	// },2000)

	const goset = (e) => {
		if (e == 1) {
			if (!state.userinfo.phone_number) {
				uni.showToast({
					title: '好友不存在，请先添加好友！',
					icon: 'none',
					duration: 2000
				});
				return
			}
			uni.navigateTo({
				url: '/pages/chat/set?targetId=' + state.userinfo.targetId
			})
		} else if (e == 2) {
			uni.navigateTo({
				url: '/subPackages/addressbook/userinfo/index?portaltype=1&type=1&system_code=' + state.userinfo.targetId
			})
		}

	}
	const oncopy = (item) => {
		state.thiscode = null
		uni.setClipboardData({
			data: item.text,
			success: function () {
				uni.showToast({
					title: '复制成功',
					icon: 'success',
					duration: 2000
				});
			}
		});
	}

	// let setdata=(newValue)=>{
	// 	scrollLeftTop.value = null
	// 	let obj = newValue;
	// 	let keys = Object.keys(obj);
	// 	let lastKey = keys[keys.length - 1];
	// 	lastids.value = lastKey

	// 	// nextTick(() => {
	// 	// 	setTimeout(() => {
	// 	// 		scrollLeftTop.value = 'lastid'
	// 	// 		setTimeout(() => {
	// 	// 			lastids.value = null
	// 	// 		}, 150)

	// 	// 	}, 200)
	// 	// })

	// }

	// watch(() => store.state.getMessages, (newValue, oldValue) => {
	// 	if (newValue) {
	// 		throttle(setdata(newValue), 2000)
	// 	}
	// }, {
	// 	deep: true, immediate: true
	// });


	onUnload(() => {
		store.commit('settargetId', null)//清空会话id
		store.commit('cleargetMessages')
		store.commit('setnolist', false)

	})

	const scrollLeftTop = ref<any>(null)

	let callback = {
		onMessageSaved: (res) => {
			console.log('onMessageSavedonMessageSaved', res)
			//...
		},
		onMessageSent: (res) => {
			if(res.code==405){
				uni.showToast({
					title: '对方已把你拉黑，发送失败！',
					icon: 'none',
					duration: 2000
				});
				
			}
			
			
			if (res.code == 0) {
				//store.dispatch('getMessages', state.userinfo.targetId,0)
				

			}
			
			setTimeout(()=>{
				let datas = {
					num: 0,
					targetId: null,
					type: 1,
					targetId: state.userinfo.targetId,
				
				}
				
				store.dispatch('getConversations', datas)
			},200)
			//...
		}

	};





	const doSearch = async (e) => {//发送文本
		if (!state.userinfo.phone_number) {
			uni.showToast({
				title: '好友不存在，请先添加好友！',
				icon: 'none',
				duration: 2000
			});
			return
		}


		let message = {

		}


		if (e == 1) {//发送文本
			message = {
				text: state.content,
				conversationType: 1,
				targetId: state.userinfo.targetId,
				extra: '',
				content: state.content,
				messageType: 2,

				// channelId:'',//所属会话的业务标识，长度限制 20 字符 
				// conversationType:1,//会话类型   chatroom: 3聊天室会话   group: 2 群聊会话   private: 1 单聊会话   system: 4 系统会话   ultraGroup: 5 超级群会话   
				// direction:0,//receive: 1 接受方   send: 0 发送方
				// expansion:{},//消息扩展信息列表
				// extra:'',//消息附加字段
				// //groupReadReceiptInfo：{}   hasRespond boolean   readReceiptMessage boolean   respondUserIds boolean 群阅读回执状态
				// //mentionedInfo:{} mentionedContent string 包含 @ 提醒的消息，本地通知和远程推送显示的内容   type 0所有人 1指定的人 @ 提醒的类型   userIdList[] @ 的用户 ID 列表
				// messageType:2, //10 命令   11命令通知   1自定义   5文件   7git图   4image图   12位置消息   8撤回   9引用   6小视频   2文本   0无效类型   13用户自定义消息   3语音
				// //messageUId //服务器消息唯一 ID（在同一个 Appkey 下全局唯一）
				// offLine:false,//是否是离线消息，只在接收消息的回调方法中有效，如果消息为离线消息，则为 YES ，其他情况均为 NO
				// //pushOptions: //消息推送配置
				// receivedStatus:0,//3已下载   2已听   5该消息是被多端同时收取的   1已读   4该消息是被多端同时收取的   0未Agu 
				// receivedTime: new Date().getTime(),
				// senderUserId:store.state.myinfo.system_code,
				// sentStatus:2,//canceled: 6 对方已取消   destroyed: 5 对方已销毁   failed: 1 发送失败   read: 4 对方已读   received: 3 对方已接收   sending: 0 发送中   sent: 2 已发送
				// targetId:state.userinfo.targetId,
				//userInfo:{} //消息携带的用户信息  alias 备注   extra 附加信息。   name 名称（昵称）。   portrait 用户头像地址。   userId 用户 id。
			}



		} else if (e == 2) {//发送个人名片
			// message = {
			// 	text: store.state.myinfo.name_cn,
			// 	conversationType: 1,
			// 	targetId: state.userinfo.targetId,
			// 	extra: '',
			// 	content: store.state.myinfo.name_cn+'1',
			// 	messageType: 1,
			// 	expansion:{
			// 		img:store.state.myinfo.avatar,
			// 		name:store.state.myinfo.name_cn,
			// 		system_code:store.state.myinfo.system_code,
			// 		targetId:store.state.myinfo.system_code
			// 	}
			// }



			/* message = await store.state.engine.createCustomMessage(
				type: 1,
				targetId: state.userinfo.targetId,
				channelId: null,
				policy: 1,
				messageIdentifier: 'chat_diy',
					fields: {
					img: store.state.myinfo.avatar,
					name: store.state.myinfo.name_cn,
					system_code: store.state.myinfo.system_code,
					targetId: store.state.myinfo.system_code
				}
			); */

	

	
			let fields = {
				img: store.state.myinfo.avatar,
				name: store.state.myinfo.name_cn,
				system_code: store.state.myinfo.system_code,
				targetId: store.state.myinfo.system_code
			}

			message = await store.state.engine.createCustomMessage(
				1,
				state.userinfo.targetId,
				null,
				1,
				'chat_diy',
				fields
			);


		}


		let code = await store.state.engine.sendMessage(message, callback);
		state.content = ""

	}


	const sendMediaMessage = async (local) => {//发送媒体消息
		let listener = {
			onMediaMessageSaved: (res) => {
				console.log('onMediaMessageSaved', res)
				//...
			},
			onMediaMessageSending: (res) => {
				console.log('onMediaMessageSending', res)
				//...
			},
			onSendingMediaMessageCanceled: (res) => {
				console.log('onSendingMediaMessageCanceled', res)
				//...
			},
			onMediaMessageSent: (res) => {
				console.log('onMediaMessageSent', res)
				if (res.code == 0) {
					//store.dispatch('getMessages', state.userinfo.targetId,0)
					let datas = {
						num: 0,
						targetId: null,
						type: 1,
						targetId: state.userinfo.targetId,

					}

					store.dispatch('getConversations', datas)

				}
				//...
			}

		};

		let message = {
			local,
			targetId: state.userinfo.targetId,
			conversationType: 1,
			messageType: 4

		}
		let code = await store.state.engine.sendMediaMessage(message, listener);
	}


	const senimgfun = (e) => {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: e == 1 ? ['album'] : ['camera'], //从相册选择
			success: function (res) {
				console.log('resresresresresresresres', res);
				if (res.errMsg == "chooseImage:ok") {
					if (e == 1) {
						sendMediaMessage(res.tempFilePaths[0])
					} else {
						var p = plus.io.convertLocalFileSystemURL(res.tempFilePaths[0]);
						sendMediaMessage('file:///' + p)
					}

				}
			}
		});
	}


	const navigationinfo = ref<any>(uni.getStorageSync('navigationinfo'))

	const getlist = () => {
		console.log('store.state.getMessages[0]store.state.getMessages[0]', store.state.getMessages[0].sentTime)
		let datas = {
			targetId: state.userinfo.targetId,
			times: store.state.getMessages[store.state.getMessages.length - 1].sentTime,
			type: 1,
			status: 1
		}
		store.dispatch("getMessages", datas)
	}

	const loadMore = throttle(getlist, 100)

	const oninit = (targetId) => {
		//console.log('e.targetIde.targetIde.targetId', e.targetId)
		// state.userinfo = JSON.parse(decodeURIComponent(e.result));
		// console.log(11111111,state.userinfo)
		state.userinfo.targetId = targetId


		let timefilter = store.state.conversationList.filter(item => item.targetId == state.userinfo.targetId)[0]
		console.log('store.state.conversationList.filter(item => item.targetId ==state.userinfo.targetId)', store.state.conversationList.filter(item => item.targetId == state.userinfo.targetId))
		let datas = {
			targetId: state.userinfo.targetId,
			times: timefilter?.operationTime || Date.now()
		}
		console.log()
		store.dispatch("getMessages", datas)

		friend_info({
			unique_code: state.userinfo.targetId
		}).then(res => {
			console.log('聊天好友信息', res.data)
			state.userinfo = res.data
			state.userinfo.phone_number == null
			state.userinfo.targetId = targetId
			let friendinfo = uni.getStorageSync('friendinfo')
			friendinfo[state.userinfo.targetId].remark_name = res.data.remark_name
			friendinfo[state.userinfo.targetId].avatar = res.data.contact_user_avatar
			friendinfo[state.userinfo.targetId].system_code = res.data.system_code
			uni.setStorageSync('friendinfo', friendinfo)
			store.commit('setfriendinfo', friendinfo)

			///console.log('store.state.friendinfostore.state.friendinfo',store.state.friendinfo)



			// "contact_user_avatar": "https://fan-qr-code.oss-cn-shenzhen.aliyuncs.com/ea099e61-9bc3-4b3d-afb1-081614c98527.jpg",
			// "description": "",
			// "is_favourite": false,
			// "source": "搜索加好友",
			// "remark_name": "小帅",
			// "signature": "国服第一深情",
			// "phone_number": "18126193631",
			// "remark_phone_number": "",
			// "system_code": "SC241230093316ENVMLWH8",
			// "add_time": "2025-01-06 18:02:08"
			console.log('resresresresresresresresresresresresresresres', res)
		}).catch(res => {

		})
	}

	onShow(() => {
		if (uni.getStorageSync('above_info')) {//从个人信息---聊天页面跳过来的
			store.commit('settargetId', null)//清空会话id
			store.commit('cleargetMessages')
			store.commit('setnolist', false)

			oninit(uni.getStorageSync('above_info').targetId)
			console.log('222222222222', uni.getStorageSync('above_info').targetId)

			uni.setStorageSync('above_info', '')
		}

		if (uni.getStorageSync('forwardtype')) {
			uni.setStorageSync('forwardtype', null)
			uni.showToast({
				title: '发送成功',
				icon: 'success',
				duration: 2000
			});
		}
	})

	onLoad(async(e) => {
		if(e.type==1){//如果是搜索进来的
			state.time = e.time
			state.chattype=e.type
		}
		if (e.targetId) {
			state.targetId = e.targetId
			
			// let callback = {
			// 	onUnreadCountCleared: (res) => {
			// 		console.log()
			// 	}
			// };
			// let code = await store.state.engine.clearUnreadCount(1, e.targetId, null,  new Date().getTime()+1000, callback);
		}

	})
	
	
	onShow(async(e) => {
		if (state.targetId) {
			oninit(state.targetId)
		}
	})
	
	const state = reactive({
		targetId:null,
		chattype:null,
		time:null,
		onmultip: false,
		chatinputmoretype: false,
		thiscode: null,
		inputboxsheight: 0,
		scrollviewheight: 0,
		userinfo: {
			targetId: null,
			phone_number: null
		},
		content: '',
	})
</script>
<style>

</style>

<style scoped lang="scss">
	$ztcolor: #39C7C1;

	.zttecolor {
		color: $ztcolor;
	}

	.ztbgcolor {
		background-color: $ztcolor;
	}

	.colorf9 {
		background: #F9F9F9;
	}

	.bgbox {
		width: 100vw;
		height: 100vh;
		// overflow: hidden;

		//background: linear-gradient(180deg, #F0F4FE 0%, #FFFFFF 40%, #FFFFFF 100%);

	}

	.addsclass {
		width: 30upx;
		height: 7upx;
		top: 0;
		right: 24upx;
		bottom: 0;
		margin: auto 0;
	}

	.inputboxs {
		bottom: 0;
		background: #F4F7F7;
		min-height: 150upx;
		width: 100%;
	}

	.inputclassbox {
		height: 96upx;
		border-radius: 48upx;
	}

	.bottomfsbq {
		width: 52upx;
		height: 52upx;
	}

	.userimgs {
		width: 84upx;
		height: 84upx;
		border-radius: 30upx;
	}

	.dialoguecontent {
		max-width: 460upx;
		border-radius: 0 20upx 20upx 20upx;
		position: relative;
		background-color: #ffffff;
	}

	.dialoguecontent2 {
		max-width: 460upx;
		border-radius: 20upx 0 20upx 20upx;
		position: relative;
		background-color: #2DB8B2;
	}

	.operateclass1 {
		background: #2F3736;
		// width: 500upx;
		height: 90upx;
		right: 0;
		top: -110upx;
		border-radius: 20upx;
	}

	.operateclass2 {
		background: #2F3736;
		// width: 500upx;
		height: 90upx;
		left: 0;
		top: -110upx;
		border-radius: 20upx;
	}

	.operateclassimg {
		width: 38upx;
		height: 38upx;
		// margin-bottom: 6upx;
	}

	.addboxssj1 {
		position: absolute;
		bottom: -31upx;
		/* 我们只是在视觉上将另外三个边框隐藏掉了，盒子的大小仍然是边框宽度的2倍 */
		left: 30upx;
		width: 0;
		height: 0;
		border: 16upx solid transparent;
		border-top-color: #2F3736;
	}

	.addboxssj2 {
		position: absolute;
		bottom: -31upx;
		/* 我们只是在视觉上将另外三个边框隐藏掉了，盒子的大小仍然是边框宽度的2倍 */
		right: 30upx;
		width: 0;
		height: 0;
		border: 16upx solid transparent;
		border-top-color: #2F3736;
	}

	.chatinputimg {
		width: 120upx;
		height: 120upx;
	}

	.multipleclass {
		margin-top: 25upx;
		margin-right: 16upx;
		width: 30upx;
		height: 30upx;
		border-radius: 50%;
		border: 2upx solid #D0D0D0;
	}

	.multipleclass2 {
		margin-top: 25upx;
		margin-right: 16upx;
		width: 34upx;
		height: 34upx;
	}

	.grmpclass1 {
		width: 460upx;
		border-radius: 0 20upx 20upx 20upx;
	}

	.grmpclass2 {
		width: 460upx;
		border-radius: 20upx 0 20upx 20upx;
	}

	.scrollview {
		background-repeat: no-repeat;
		background-size: cover;
		background-position: center center;
	}
</style>